<template>
    <div>
        <el-input v-model="searchInfo" style="width: 50%" placeholder="搜素" clearable @input="searchInfoChange()"/>
        <el-button type="primary" style="margin-left: 2%" :loading="saveLoading" @click="saveInfo()">确 认</el-button>
        <el-table
            :data="filterInfoList"
            style="width: 100%; margin-bottom: 20px; margin-top: 20px;"
            row-key="id"
            border
            :stripe="true"
            :show-overflow-tooltip="true"
            ref="tableRef"
            class="tableContainer"
            max-height="50vh"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" :reserve-selection="true"/>
            <el-table-column v-for="item in propJson.tableFieldList"
                             :prop="item.variableField"
                             :label="item.variableLabel"
                             :align="item.isAlignCenter">
                <template #default="scope" v-if="item.showType === 'custom'">
                    <slot :name="item.variableLabelEN" :scope="scope"></slot>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import {commonParamChange, getCommonParamInfo, sleep} from "@/utils/commonParamUtil";
import {buildRequestParam, MSOARequest} from "@/utils/serviceRequestUtil";
import request from "@/utils/request";
import jsonpath from "jsonpath";
import {ElNotification} from "element-plus";

export default {
    name: "TableSelectionSearchComponent",
    props: ['propJson', 'commonParam'],
    data() {
        return {
            infoList: [],
            filterInfoList: [],
            searchInfo: '',
            saveLoading: false,
            mountedFlag: false
        }
    },
    methods: {
        handleSelectionChange(val) {
            // 修改关联的变量值
            commonParamChange(this.commonParam, this.propJson.selectVarParamName, val)
        },
        searchInfoChange() {
            this.filterInfoList = [];
            // 遍历所有数据，查询出符合条件的数据
            this.infoList.forEach(res => {
                // 遍历需要过滤的字段
                for (let i = 0; i < this.propJson.tableSelectField.length; i++) {
                    let temp = this.propJson.tableSelectField[i]
                    if (temp in res) {
                        if (res[temp].includes(this.searchInfo)) {
                            this.filterInfoList.push(res)
                            break;
                        }
                    }
                }
            })
        },
        execThen(awaitObj) {
            awaitObj.flag = false;
        },
        execCatch(awaitObj) {
            awaitObj.flag = false;
            awaitObj.res = false;
        },
        doSubmitMSSA(buildRes, awaitObj, submitAction) {

        },
        doSubmitMSOA(buildRes, awaitObj, submitAction) {
            MSOARequest(buildRes, submitAction.apiMethod, submitAction.apiPath,
                submitAction.apiResponseList, this.commonParam,
                this.execThen, this.execCatch, awaitObj)
        },
        doSubmitRTSA(buildRes, awaitObj, submitAction) {

        },
        doSubmitApi(submitAction, awaitObj) {
            // 构建入参
            let paramList = submitAction.apiParamList
            let buildRes = buildRequestParam(this.commonParam, paramList)
            // 根据api类型调用方法
            if (submitAction.apiType === "MSSA") {
                this.doSubmitMSSA(buildRes, awaitObj, submitAction)
            } else if (submitAction.apiType === "MSOA") {
                this.doSubmitMSOA(buildRes, awaitObj, submitAction)
            } else if (submitAction.apiType === "RTSA") {
                this.doSubmitRTSA(buildRes, awaitObj, submitAction)
            } else {
                awaitObj.flag = false
            }
        },
        doSubmitVariable(submitAction, awaitObj) {
            // 获取字段名称
            let paramName = submitAction.variableParamName;
            // 获取要设置的值
            let value = submitAction.variableValue;
            commonParamChange(this.commonParam, paramName, value)
            awaitObj.flag = false
        },
        async saveInfo() {
            this.saveLoading = true
            // 定义一个标志位，后续同步执行
            let awaitObj = {flag: false, res: true}
            // 遍历所有的取消动作
            for (let i = 0; i < this.propJson.submitActionList.length; i++) {
                let submitAction = this.propJson.submitActionList[i];
                // 根据不同的类型进行不同的处理
                let type = submitAction.type;
                while (awaitObj.flag) {
                    await sleep(1)
                }
                if (type === "api") {
                    awaitObj.flag = true
                    this.doSubmitApi(submitAction, awaitObj);
                } else if (type === "variable") {
                    awaitObj.flag = true
                    this.doSubmitVariable(submitAction, awaitObj)
                }
            }
            this.saveLoading = false
            if (awaitObj.res) {
                ElNotification({
                    title: 'Success',
                    message: "成功",
                    type: 'success'
                });
            } else {
                ElNotification({
                    title: 'Error',
                    message: "失败",
                    type: 'error'
                });
            }
        },
        doCustom() {
            if (this.propJson.tableDataCustomType === "Array") {
                if (Array.isArray(this.propJson.tableDataCustomInfo)) {
                    this.filterInfoList = this.propJson.tableDataCustomInfo
                    this.infoList = this.propJson.tableDataCustomInfo
                } else {
                    let newStr = this.propJson.tableDataCustomInfo.replaceAll("\'", "\"");
                    let infoList = JSON.parse(newStr)
                    this.filterInfoList = infoList
                    this.infoList = infoList
                }
            }
            this.mountedFlag = true
        },
        doVariable() {
            let res = getCommonParamInfo(this.commonParam, this.propJson.tableDataVariableParam)
            this.filterInfoList = res
            this.infoList = res
            this.mountedFlag = true
        },
        doMSOA(buildRes) {
            let methodType = "";
            if (this.propJson.apiMethod === 'GET') {
                methodType = "get";
            } else if (this.propJson.apiMethod === 'POST') {
                methodType = "post";
            }
            request({
                url: this.propJson.apiPath,
                method: methodType,
                data: buildRes
            }).then(res => {
                let jsonRes = jsonpath.query(res, this.propJson.responseJsonPath)
                this.filterInfoList = jsonRes
                this.infoList = jsonRes
                this.mountedFlag = true
            })
        },
        doMSSA(buildRes) {

        },
        doRTSA(buildRes) {

        },
        doApi() {
            if (this.propJson.editFlag) {
                return
            }
            // 构建参数
            let paramList = this.propJson.queryListRequestList
            let buildRes = buildRequestParam(this.commonParam, paramList)
            // 服务调用
            if (this.propJson.apiType === "MSSA") {
                this.doMSSA(buildRes)
            } else if (this.propJson.apiType === "MSOA") {
                this.doMSOA(buildRes)
            } else if (this.propJson.apiType === "RTSA") {
                this.doRTSA(buildRes)
            }
        },
        getInfoList() {
            // 判断表格的数据类型
            if (this.propJson.tableDataType === "custom") {
                this.doCustom()
            } else if (this.propJson.tableDataType === "variable") {
                this.doVariable()
            } else if (this.propJson.tableDataType === "api") {
                this.doApi()
            }
        },
        doSelectedCustom() {
            if (this.propJson.selectedDataCustomType === "Array") {
                if (Array.isArray(this.propJson.selectedDataCustomInfo)) {
                    let data = this.propJson.selectedDataCustomInfo
                    this.resetSelectList(data)
                } else {
                    let newStr = this.propJson.selectedDataCustomInfo.replaceAll("\'", "\"");
                    let infoList = JSON.parse(newStr)
                    this.resetSelectList(infoList)
                }
            }
        },
        doSelectedVariable() {
            let res = getCommonParamInfo(this.commonParam, this.propJson.selectedDataVariableParam)
            this.resetSelectList(res)
        },
        doSelectedApi() {
            // 构建参数
            let paramList = this.propJson.selectedListRequestList
            let buildRes = buildRequestParam(this.commonParam, paramList)
            // 服务调用
            if (this.propJson.selectedApiType === "MSSA") {
                this.doSelectedMSSA(buildRes)
            } else if (this.propJson.selectedApiType === "MSOA") {
                this.doSelectedMSOA(buildRes)
            } else if (this.propJson.selectedApiType === "RTSA") {
                this.doSelectedRTSA(buildRes)
            }
        },
        resetSelectList(data) {
            data.forEach(info => {
                for (let i = 0; i < this.infoList.length; i++) {
                    // 根据要匹配的字段进行匹配
                    let matchField = this.propJson.selectedMatchField
                    if (this.infoList[i][matchField] === info[matchField]) {
                        this.$refs.tableRef.toggleRowSelection(this.infoList[i], true);
                    }
                }
            })
        },
        doSelectedMSOA(buildRes) {
            let methodType = "";
            if (this.propJson.selectedApiMethod === 'GET') {
                methodType = "get";
            } else if (this.propJson.selectedApiMethod === 'POST') {
                methodType = "post";
            }
            request({
                url: this.propJson.selectedApiPath,
                method: methodType,
                data: buildRes
            }).then(res => {
                let jsonRes = jsonpath.query(res, this.propJson.selectedResponseJsonPath)
                this.resetSelectList(jsonRes)
            })
        },
        doSelectedMSSA(buildRes) {

        },
        doSelectedRTSA(buildRes) {

        },
        async doMounted() {
            while (!this.mountedFlag) {
                await sleep(0.5)
            }
            this.$refs.tableRef.clearSelection(false);
            // 判断表格的数据类型
            if (this.propJson.selectedDataType === "custom") {
                this.doSelectedCustom()
            } else if (this.propJson.selectedDataType === "variable") {
                this.doSelectedVariable()
            } else if (this.propJson.selectedDataType === "api") {
                this.doSelectedApi()
            }
        }
    },
    mounted() {
        if (this.propJson.editFlag) {
            return
        }
        this.doMounted()
    },
    created() {
        // 获取列表
        this.getInfoList();
    }
}
</script>

<style scoped lang="less">

</style>